/**
 * Copyright (C)  Gadglet .
 *
 * This file is part of Gadglet
 *
 * Gadglet is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Gadglet is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Gadglet. If not, see <http://www.gnu.org/licenses/>.
 */

package com.gadglet.client.gwt.core.ui;

import com.gadglet.client.gwt.GadgetUtils;
import com.gadglet.client.gwt.core.GadgletRequest;
import com.gadglet.client.gwt.core.ResponseHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.gadgets.client.impl.PreferencesUtil;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * This class create the registration window for both OAuth and 
 * Bizlet registration
 *
 */
public class UserRegistration {
	private GadgletRequest activeRequest =null;
	private String registrationUrl = null;
	private String winParams = null;
	private ResponseHandler activeHandler;

	/**
	 * Set parameters to open the registration window default "width=600,height=500"
	 * @param winParams - parameters to open the registration 
	 */
	public void setRegWinParams(String winParams){
		this.winParams = winParams;
	}
	
	private String getRegWinParams(){
		return this.winParams;
	}

		
	private DialogBox dialogBox;
	private HTML detailsHTML;
	final Button dialogButton = new Button();
	
	protected final PreferencesUtil prefs = PreferencesUtil.nativeInitPrefs();

	public UserRegistration() {
		dialogBox = new DialogBox();
		dialogBox.setAnimationEnabled(true);
				
		detailsHTML = new HTML();
		detailsHTML.setVisible(true);
	

		VerticalPanel dialogVPanel = new VerticalPanel();
		dialogVPanel.setStylePrimaryName("error-panel");
		dialogVPanel
				.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		
		ScrollPanel panel = new ScrollPanel(detailsHTML);
		panel.setSize("200px", "100px");

		FlowPanel buttons = new FlowPanel();

		buttons.add(dialogButton);
		dialogVPanel.add(panel);
		dialogVPanel.add(buttons);
		dialogBox.setWidget(dialogVPanel);
	}

	
	public void register(String url,GadgletRequest request,ResponseHandler handler) {
		registrationUrl  = url;
		dialogButton.setVisible(true);
		dialogBox.setText(prefs.getMsg("gadgetLabelRegistrationProcess"));
		detailsHTML.setHTML(prefs.getMsg("gadgetMsgUserIsNotRegistered"));
		dialogButton.setText(prefs.getMsg("gadgetLabelRegister"));
		activeRequest = request;
		activeHandler= handler;
		
		dialogButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				try{
				open(registrationUrl, getRegWinParams());
				dialogButton.setVisible(false);
				detailsHTML.setHTML(prefs.getMsg("gadgetMsgUserIsRegistrating"));
				}
				catch (Exception e){
					// try and solve ie8 issue
					detailsHTML.setText(e.getMessage());
				}
			}
		});
		dialogBox.center();
	}
	
	public void approveOAuth(String url,GadgletRequest request, ResponseHandler handler) {
		registrationUrl  = url;
		dialogButton.setVisible(true);
		dialogBox.setText(prefs.getMsg("gadgetLabelSecurityApproval"));
		detailsHTML.setHTML(prefs.getMsg("gadgetMsgPleaseApprovePlatform"));
		dialogButton.setText(prefs.getMsg("gadgetLabelApprove"));
		activeRequest = request;
		activeHandler= handler;
		dialogButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				open(registrationUrl,null);
				dialogButton.setVisible(false);
				detailsHTML.setHTML(prefs.getMsg("gadgetMsgUserApprovingPlatform"));
			}
		});
		
		if (GadgetUtils.isCanvasView())
			GadgetUtils.dialogBoxTop(dialogBox);
		else
			dialogBox.center();
		
	}
	
	
	  /**
	   * open window, then start a process to watch for it to close
	   * 
	   * @param url - oauth approval url
	   */
	  private void open(String url, String winParam) {
		  
	
		  
		if(winParam!=null && !winParam.isEmpty())
			openWindow(url,winParam);
		else
			openWindow(url,"width=600,height=500");
		  
	    loop();
	  }

	  /**
	   * open new window
	   *  "_blank",
	   * @param url - oauth approval url
	   * @return
	   */
	  private final native void openWindow(String url, String winParam) /*-{
	    $wnd.winHandle = $wnd.open(url, "_blank",winParam);
	  }-*/;
	  
	  /**
	   * is popup window still open
	   * 
	   * @return - boolean
	   */
	  private final native boolean isWindowClosed() /*-{
	    var b = false;
	    // TODO check for undefined window
	    if ($wnd.winHandle.closed == true) {
	      b = true;
	      //debug
	      $wnd.winHandle = null;
	    }
	
	    return b;
	  }-*/;
	  
	  /**
	   * loop, watching for window to close
	   * 
	   */
	  private void loop() {
	    Timer t = new Timer() {
	      @Override
		public void run() {
	        if (isWindowClosed() == true) {
	          setWindowClosed();
	          return;
	        }
	        loop();
	      }
	    };
	    t.schedule(100);
	  }
	  
	  /**
	   * call this when the window closes
	   */
	  public void setWindowClosed() {
		  dialogBox.hide();
	    
		  activeRequest.makeRequest(activeHandler);
	    
	  }

}
